import {Spin} from "antd";
import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import SelectTransfer from "../../../module/dataForm/SelectTransfer.tsx";
import BaseForm from "../../../module/form/BaseForm.tsx";
import {getFormView} from "../../../services/ViewService.tsx";
import {addOkModal, closeModal} from "../../../services/ModalService.tsx";
import useThrottle from "../../../customUse/useThrottle.tsx";
import {createParams, getObjByRule} from "../../../utils";
import {AxiosGet, AxiosSer} from "../../../services/HttpService.tsx";
import {useTranslation} from "react-i18next";

interface AddUserGroupModalProps {
    modalKey: string,
    viewName: string,
    type: string,
    dataSource: any,
    flowData: any[],
    url: string,
    getUrl: string,
    selectKey: string,
    getParams?: any,
    method: string,
    transferField?: string[],
    transferProps?: string[],
}

const AddUserGroupModal: FC<AddUserGroupModalProps> = (props) => {
    const {transferField = ["alternativeRoles", "containRoles"], selectKey = "", transferProps = {}} = props

    const {t} = useTranslation();
    const fromRef = useRef(),
        selectKeysRef = useRef("");

    const [loading, setLoading] = useState(false),
        [view, setView] = useState(undefined),
        [data, setData] = useState(undefined);

    const isCreate: Function = useCallback(() => {
        return props.type === "create";
    }, [props.type]);

    const isEdit: Function = useCallback(() => {
        return props.type === "edit";
    }, [props.type]);


    const loadData = useCallback(async () => {
        let {flowData, getUrl, getParams = {}, viewName, dataSource = {}} = props;
        let editData = !isCreate() && flowData ? {...flowData[0]} : {};
        const params = getObjByRule(editData, getParams)
        setLoading(true);
        let {data = {}} = await AxiosGet(getUrl, params);
        const leftData = data[transferField[0]];
        const rightData = data[transferField[1]];
        let result = await getFormView(viewName, {...data}, dataSource);
        setLoading(false);
        selectKeysRef.current = rightData.map(i => i.id).join(",");
        setView(result.form);
        setData([...leftData, ...rightData])
    }, [props.type, props.viewName])

    useEffect(() => {
        loadData();
    }, [props.viewName]);


    const onOk = useThrottle(async () => {
        const {url, method} = props;
        const values = await fromRef.current.validateFields();
        let params = {
            ...values,
            [selectKey]: selectKeysRef.current.split(",").filter(i => i).map(i => ({id: i}))
        }
        const newParams = createParams(params, props);
        const methodType = method ? method : (isEdit() ? "PUT" : "POST");
        setLoading(true);
        const result = await AxiosSer(url, methodType, {
            ...newParams
        }, true) || {};
        setLoading(false);
        result.code == "1" && await closeModal(props.modalKey, async () => {
            return {data: newParams, ...result};
        });

    }, 2000, [props.modalKey, props.type, props.selectKey]);


    useEffect(() => {
        addOkModal(props.modalKey, onOk);
    }, []);

    const handleChange = useCallback((selectKeys) => {
        selectKeysRef.current = selectKeys
    }, [])


    const renderAddUserGroupModal = useMemo(() => {
        if (!view) {
            return null
        }
        const {titles = []} = transferProps
        return (
            <Spin spinning={loading} wrapperClassName="sf_core_add_user_group">
                <div className="sf_core_add_user_group_form">
                    <BaseForm
                        init={fromRef}
                        view={view}
                        formItemLayout={1}
                    />
                </div>
                <div className="sf_core_add_user_group_transfer">
                    <SelectTransfer
                        width={400}
                        height={400}
                        transferField={transferField}
                        {...transferProps}
                        titles={titles.map(k => (t(k)))}
                        dataSource={data}
                        value={selectKeysRef.current}
                        format={{
                            key: "id",
                            label: "name"
                        }}
                        onChange={handleChange}
                    />
                </div>
            </Spin>
        )
    }, [loading, view, data]);

    return (renderAddUserGroupModal);
};

export default React.memo(AddUserGroupModal);